<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Models\Goods;
use App\Models\Goodsimg;
use App\Types;

//使用类
use App\Http\Controllers\Controller;

//后台商品控制器
class GoodsController extends Controller
{
    //商品首页
    public function index(Request $request){
        //操作数据库
        $data=Goods::orderBy("id","desc")->paginate(10);

        //dd($data);
        //处理小图
        foreach ($data as $key => $value){
          $value->tupian = Goodsimg::where("gid",$value->id)->get();

        }
       // dd($data);
        //加载页面
        return view("admin.goods.index")->with("data",$data);
    }

    //商品的添加页面
    public function create(){
        //查询分类
      $data = Types::Select("*",\DB::raw('concat(path,id) as p'))->orderBy('p')->get();
//dd($data);

        //数据处理
        foreach($data as $key => $value){
           // var_dump($value);exit;
            $arr=explode(',',$value->path);//把字符串打散为数组
           $size = count($arr);
           $value->size=$size-2;//判断几级分类
            //str_repeat() 字符串重复指定的次数  $value['html']
           $value->html=str_repeat('|--',$size-2).$value->name;

        }
        //dd($data);
       // exit;

        //加载页面
        return view("admin.goods.add",[
            "data"=>$data
        ]);
    }

    //处理商品的插入操作
    public function store(Request $request){
       // dd($request->all());
        //获取多图
        $imgs = $request->input("imgs");

        //移除不需要的字符
        $data = $request->except("_token","imgs");

        //插入数据库
        if($id = Goods::insertGetId($data)){
            //处理商品多图片
            $arr=explode(',',$imgs);//字符串 变 数组
            foreach ($arr as $key => $value){//遍历图片数组
                $brr = array();

                $brr['gid']=$id;
                $brr['img']=$value;
                Goodsimg::insert($brr);
            }

            return redirect('admin/goods');

        }else{
            return back();
        }


    }


	
}
